package bim.controller;

import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;

import bim.dao.UserDao;
import bim.domain.User;
import bim.security.AnonymousUserAdapter;
import bim.security.UserAdapter;

@Controller
public class BaseController {//extends KeterBaseController 
    
    @Autowired
    protected Validator validator;

    @Autowired
    UserDao dao;
    
    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    public BaseController() {
      
    }

	/**
	 * <p>Method ：populateCurrentUser
	 * <p>Description : 将当前用户放入JSTL全局变量
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@ModelAttribute("user")
	public User populateCurrentUser() {
		return getCurrentUser();
	}

	public User getCurrentUser() {
        if(!isLoggedIn()){
            return null;
        }
        return getCurUser().getUser(true);    
    }
	

	/**
	 * Returns UserAdapter object for the currently logged in user, or null if
	 * no User is logged in.
	 * 
	 * @return currently logged user or null
	 */
	private UserAdapter getCurUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		if (authentication != null) {
			Object principal = authentication.getPrincipal();
			if (principal instanceof UserAdapter) {
				return ((UserAdapter) principal);
			}
		}

		return new AnonymousUserAdapter();
	}

	/**
	 * Utility method to determine if the current user is logged in.
	 * 
	 * @return true if user is logged in
	 */
	private boolean isLoggedIn() {
		return !(getCurUser() instanceof AnonymousUserAdapter);
	}
    
}